20. Exercise: Add End Game Event
L5 31 LiveData And Events SC 1
Now it’s your turn to complete this exercise yourself.
Let's add the end game event.
1. Make a properly encapsulated LiveData called eventGameFinish that holds a boolean:
You'll create this LiveData in the GameViewModel. Check out word and score to see how to do this.
2. Make the function onGameFinishComplete which makes the value of eventGameFinish false:
This function simply sets the value of _eventGameFinish to false. This is to signal that you've handled the game finish event and that you don't need to handle it again. In this specific example, it's a way to say you've done the navigation.
3. Set eventGameFinish to true, to signify that the game is over:
In the GameViewModel, find the condition where the wordList is empty. If it's empty, the game is over, so signal that by setting the value of eventGameFinish to true.
4. Add an observer of eventGameFinish:
Back in GameFragment, add an observer of eventGameFinish.
In the observer lambda you should:
- Make sure that the boolean holding the current value of
eventGameFinishedis true. This means the game has finished. - If the game has finished, call
gameFinished. - Tell the view model that you've handled the game finished event by calling
onGameFinishComplete.
Run your code and make sure that when you go through all of the words that the game does in fact finish. When it finishes, it should navigate you to the score screen.
If you want to start at this step, you can download this exercise code from: Step.05-Exercise-Add-End-Game-Event.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.05-Solution-Add-End-Game-Event or using this git diff.
Task Description:
Check the steps below as you implement them to complete this exercise.
Task Feedback:
Great work! You can check your solution against the solution we’ve provided here Step.05-Solution-Add-End-Game-Event or using this git diff.
Reference documentation